﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Soft
{
    [Serializable]
    public abstract class baseObject : ICloneableEx
    {

        /// <summary>
        /// 根据栈帧获取方法的名称
        /// </summary>
        /// <param name="skipFrames"></param>
        /// <returns></returns>
        public static string GetStackMethodName(int skipFrames = 1)
        {
            MemberInfo stackMethod = baseObject.GetStackMethod(skipFrames);
            if (!(stackMethod != null))
            {
                return "";
            }
            return stackMethod.Name;
        }



        /// <summary>
        /// 根据栈帧获取方法的名称
        /// </summary>
        /// <param name="skipFrames"></param>
        /// <returns></returns>
        public static MemberInfo GetStackMethod(int skipFrames = 1)
        {
            MethodBase method = new StackFrame(skipFrames).GetMethod();
            if (method != null)
            {
                PropertyInfo propertyInfo = (from p in method.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                                             where p.GetGetMethod(true) == method || p.GetSetMethod(true) == method
                                             select p).FirstOrDefault<PropertyInfo>();
                if (propertyInfo == null)
                {
                    return method;
                }
                else
                {
                    return propertyInfo;
                }
            }
            return null;
        }




        public T Clone<T>()
        {
            if (typeof(T) != base.GetType())
            {
                throw new Exception(string.Format("不能将“{0}”类型转换成“{1}”类型。", base.GetType().FullName, typeof(T).FullName));
            }
            return (T)((object)this.Clone());
        }

        public virtual object Clone()
        {
            return base.MemberwiseClone();
        }
    }
}
